package com.heima.search.service.impl;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.ApUserSearchService;
import com.heima.search.service.ArticleSearchService;
import com.heima.utils.thread.ApThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;

@Service
@Slf4j
public class ArticleSearchServiceImpl implements ArticleSearchService {

    @Autowired
    private RestHighLevelClient client;

    @Autowired
    private ApUserSearchService apUserSearchService;


    /**
     * es文章分页查询
     * @param dto
     * @return
     * @throws IOException
     */
    @Override
    public ResponseResult search(UserSearchDto dto) throws IOException {

        //检查参数
        if(dto == null || StringUtils.isBlank(dto.getSearchWords())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //获取用户id
        ApUser user = ApThreadLocalUtil.getUser();
        if(user != null){
            //异步保存历史记录到MongoDB中
            Integer userId = user.getId();
            apUserSearchService.insert(dto.getSearchWords(),userId);
        }

        //创建请求
        SearchRequest request = new SearchRequest("app_info_article");
        //创建bool查询
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        //关键字查询
        if(dto.getSearchWords() != null){
            boolQueryBuilder.must(QueryBuilders.matchQuery("all",dto.getSearchWords()));
        }
        //最小时间
        if(dto.getMinBehotTime() != null){
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("publishTime").lte(dto.getMinBehotTime()));
        }
        request.source().query(boolQueryBuilder);
        //分页
        request.source().from(0).size(dto.getPageSize());
        //排序(按照发布时间降序排序)
        request.source().sort("publishTime", SortOrder.DESC);
        //高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.requireFieldMatch(false);
        highlightBuilder.preTags("<font style='color: red; font-size: inherit;'>");
        highlightBuilder.postTags("</font>");
        request.source().highlighter(highlightBuilder);

        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        //返回响应处理的结果
        return handleResponse(response);
    }


    /**
     * 封装处理es分页查询的响应数据
     * @param response
     * @return
     */
    private ResponseResult handleResponse(SearchResponse response) {
        List<Map> list = new ArrayList<>();
        SearchHit[] hits = response.getHits().getHits();
        for (SearchHit hit : hits) {
            Map<String,Object> map = hit.getSourceAsMap();
            //处理高亮数据
            if(hit.getHighlightFields().size() > 0){
                Text[] titles = hit.getHighlightFields().get("title").fragments();
                if(titles.length > 0){
                    map.put("h_title",titles[0].toString());
                }
            }else {
                map.put("h_title",map.get("title"));
            }
            list.add(map);
        }
        return ResponseResult.okResult(list);
    }

}
